# Create your views here.

import edg.db.User as User3
import edg.db.SimulationRun as SR

from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from edgdevelopment.reporter.models import RunID
from edgdevelopment.reporter import reportgenerator

from django.contrib import auth



def mainview(request):
	user = request.user
	return render_to_response('newdesign.html', locals())
	
#def runlist(request):
#	runid_list = RunID.objects.all()
#	return render_to_response('reporter/runids.html', locals())
	
def home(request):
        user = request.user
	return render_to_response('home.html', locals())
	
def newuser(request):
	return render_to_response('reporter/newuser.html', locals())
        
def create(request):
        u = User3
        uname = request.POST['username']
        password = request.POST['password']
        is_ok = u.isNameAvailable(uname)
        return render_to_response('reporter/newuser.html', locals())
	
def results(request):

	return render_to_response('reporter/results.html', locals())

def runlist(request):
	user = request.user
	print user
	#print dir(user)
	#runid_list = request.user.runid_set.all()
	#runid_list = SR.getRunIds(0)
        if request.user.is_authenticated():
		print "whoami"
                runid_list = request.user.runid_set.all()
        else:
                runid_list = []
	return render_to_response('reporter/runids.html', locals())

def report( request, runIDs ):
        if request.user.username != "AnonymousUser":
                print "Auth'd user"
                userid = request.user.id+1
                print "auth'd: %s" % userid
                user = request.user
        else: #anonymous
                #bit of another kludge here until users are fully implemented...
                print "Got anon!"
                user = auth.authenticate(username='AnonymousUser', password='anon')
                auth.login(request, user)
                #user = request.user
                #userid = 1
        user = request.user

        return reportgenerator.reportOn( runIDs, request, user )


################################################################################
#User auth stuff.  no touching.
################################################################################

def login(request):
        #user = request.user
        username = request.POST['username']
        password = request.POST['password']
        action = '/reporter/login'
        
        usera = auth.authenticate(username=username, password=password)
        user = usera
        if usera is not None and usera.is_active:
                auth.login(request, usera)
                return HttpResponseRedirect('/reporter/runlist')
        else:
                return render_to_response('home.html', locals())
                
                
                
def logout(request):
        auth.logout(request)
        return HttpResponseRedirect("/reporter/home")
